package com.lagou.rocketmq.rocketmq;

import com.alibaba.fastjson.JSON;
import com.lagou.rocketmq.entity.Order;
import com.lagou.rocketmq.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(topic = "queue_order_delay_topic", selectorExpression = "*", consumerGroup = "consumer_group_order_delay")
public class OrderDelayMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private OrderService orderService;

    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String orderMsg = new String(body);
        log.info("接收到延迟消息：{}", orderMsg);
        Order order = JSON.parseObject(orderMsg, Order.class);

        //检查订单状态，是否已经支付，否则设置订单超时
        if (order.getOrderId() != null) {
            Order returnOrder = orderService.timeoutOrder(order.getOrderId());
            if (null == returnOrder) {
                log.error("出现了异常！");
            }
            if ("PAID".equals(returnOrder.getStatus())) {
                log.info("订单已支付！");
                return;
            }
            if ("TIMEOUT".equals(returnOrder.getStatus())) {
                log.info("超时未支付！");
                return;
            }

        }
        log.error("出现了异常！");
    }
}
